<template>
  <el-dialog @close="close" v-model="dialogVisible" :title="title" width="50%">
    <div>
      <el-row
        :gutter="20"
        v-for="(item, index) in autoTime"
        :key="index"
        style="margin-bottom: 10px"
      >
        <el-col :span="8">
          <el-time-select v-model="item.openTime" placeholder="开启时间" />
        </el-col>
        <el-col :span="8">
          <el-time-select v-model="item.closeTime" placeholder="关闭时间" />
        </el-col>
        <el-col :span="8">
          <div style="text-align: right">
            <el-button type="primary" @click="addAutoTime" v-if="index == 0">新增</el-button>
            <el-button type="danger" @click="delAutoTime(index)" v-if="index > 0">删除</el-button>
          </div>
        </el-col>
      </el-row>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleClose(ruleFormRef)">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import { ElMessageBox, ElMessage, FormInstance, ElNotification } from 'element-plus'
import { reactive, ref } from 'vue'
import { editQuipment } from '@/api/admin'
import { useRoute } from 'vue-router'
const route = useRoute()
const loading = ref()
const saveLoading = ref(false)
const dialogVisible = ref<boolean>(false)
const title = ref('编辑设备时间')
const autoTime = ref()
const id = ref()
const emit = defineEmits(['refresh'])

function close() {
  autoTime.value = [
    {
      openTime: '',
      closeTime: '',
    },
  ]
}

const show = (item = {}) => {
  id.value = item.id
  if (item.optime) autoTime.value = item.optime
  else
    autoTime.value = [
      {
        openTime: '',
        closeTime: '',
      },
    ]
  dialogVisible.value = true
}

const addAutoTime = () => {
  let length = autoTime.value.length
  if (!autoTime.value[length - 1].openTime) {
    ElMessage.warning('请选择开启时间！')
    return
  }
  if (!autoTime.value[length - 1].closeTime) {
    ElMessage.warning('请选择关闭时间！')
    return
  }
  autoTime.value.push({
    openTime: '',
    closeTime: '',
  })
}
const delAutoTime = (index) => {
  autoTime.value.splice(index, 1)
}
const handleClose = async (done: () => void) => {
  saveLoading.value = true
  editQuipment({ id: id.value, optime: autoTime.value }).then((res) => {
    if (res.code == 200) {
      ElNotification({
        title: '编辑成功',
        message: res.msg,
        type: 'success',
      })
      emit('refresh')
      dialogVisible.value = false
    }
    saveLoading.value = false
  })
}

defineExpose({
  show,
})
</script>

